#
# Copyright (C) 2008 Erik van Oosten
#
# MIT license.
#

require 'pp'

class EmailController < ApplicationController

  # Configure your e-mail domein here.
  # For example: @EMAIL_DOMAIN = "example.com"@
  EMAIL_DOMAIN = ""

  def index
    if request.post?
      index_post if session[:virtual_domain]
      redirect_to :action => :index
    else
      unless session[:virtual_domain]
        # First time here, perform some checks.
        er = "Please set the EMAIL_DOMAIN constant in #{__FILE__}." if EMAIL_DOMAIN.empty?
        er = VirtualDomain.validate_postfix_config(EMAIL_DOMAIN) unless er
        if er
          @error_report = er
          render :action => :error_report
          return
        end
      end
      virtual_domain = session[:virtual_domain] ||= VirtualDomain.new(EMAIL_DOMAIN).load
      @dirty = virtual_domain.dirty
      @virtual_addresses = virtual_domain.virtual_addresses
      @groups = virtual_domain.groups
    end
  end

private  
  def index_post
    logger.info("email parameters:" + params.inspect)
    virtual_domain = session[:virtual_domain]
    logger.info("virtual_domain voor:" + virtual_domain.inspect)
    virtual_domain.dirty = true
    # possible actions:
    # - reset     : reload virtual file
    # - remove    : remove a user
    # - add       : add a new user
    # - activate  : activate the current state
    if params.has_key? "reset"
      virtual_domain.load
      @virtual_addresses = virtual_domain.virtual_addresses
      @groups = virtual_domain.groups
        flash[:notice] = "All changes were undone"

    else
      @virtual_addresses = virtual_domain.virtual_addresses
      @groups = virtual_domain.groups
      # process redirect and group-membership changes
      @virtual_addresses.each do |vaddr|
        vaddr.update_attributes(params["vaddr"][vaddr.user])
      end
      # always perform the 'add user'
      # Example params element:
      #  "new_vaddr"=>{"user"=>"testuser", "member_of_groups"=>{"all"=>"on", "suiker"=>"on"}, "redirect"=>"test@test.com"}
      new_user = params["new_vaddr"]["user"].strip
      if !new_user.empty? && !@groups.include?(new_user) && @virtual_addresses.all? {|vaddr| vaddr.user != new_user}
        new_vaddr = VirtualAddress.from_attributes(params["new_vaddr"])
        new_vaddr.valid?
        virtual_domain.add_user new_vaddr
      end
      # always perform the 'add group'
      new_group_name = params["new_group"].strip
      virtual_domain.add_group(new_group_name) if !new_group_name.empty? && !@groups.include?(new_group_name)
      if params.has_key? "remove"
        # remove virtual address
        @virtual_addresses.reject! {|vaddr| vaddr.user == params["remove"].keys.first}
      elsif params.has_key? "g_remove"
        # remove group
        @groups.delete(params["g_remove"].keys.first)
      elsif params.has_key? "activate"
        # activate changes
        virtual_domain.save
        virtual_domain.activate
        flash[:notice] = "Changes are activated"
      end
    end
    #input.collect {|vaddr| "<div><pre>" + vaddr.inspect + "</pre></div>"}.join("\n")
    #input.sort_by {|entry| entry.key.to_i}.collect {|vaddr| "<div><pre>" + vaddr.inspect + "</pre></div>"}.join("\n")
    #"<pre>" + input.inspect + "</pre>"
    #"<pre>" + @virtual_addresses.inspect + "</pre>"
    @virtual_addresses.each {|vaddr| vaddr.valid? }
    pp("virtual_domain na:")
    pp(virtual_domain)
    logger.info("va: " + @virtual_addresses.inspect)
  end
end
